import LiuMove from "../../components/Move.js";
import { debounce } from '../utils/utils.js';
let el = document.querySelector("[src='../common/js/move.js']");
let elStr = el.getAttribute("tag") ? el.getAttribute("tag") : 'body';
customElements.define("liu-move", LiuMove);
let liuMove = document.createElement('liu-move');
document.querySelector(elStr).appendChild(liuMove);



// 窗口按下 上下左右方向键
window.addEventListener("keydown",debounce((e,c) => {
  // let css = window.getComputedStyle(liuMove)
  // let displayStyle = css.display;
  if(window.sendSaveData){
    if(!e.ctrlKey)return;
    if (e.keyCode === 37) {
      // 左
      window.moveDirection('left', c)
    } else if (e.keyCode === 38) {
      // 上
      window.moveDirection('top', c)
    } else if (e.keyCode === 39) {
      // 右
      window.moveDirection('right', c)
    } else if (e.keyCode === 40) {
      // 下
      window.moveDirection('bottom', c)
    }


    let data = window.getData();
    window.sendSaveData(data);
  }

}, 200));



let down = false,clientX = 0, clientY = 0, timeoutId, docWidth, docHeight;
// 拖动
document.addEventListener('mousedown', (e)=>{
  if(e.button !== 0)return;
  clearTimeout(timeoutId); 
  clientX = e.clientX;
  clientY = e.clientY;
  timeoutId = setTimeout(function(){
    down = true;
    clientX = e.clientX;
    clientY = e.clientY;
    docWidth = document.documentElement.clientWidth;
    docHeight = document.documentElement.clientHeight;
    document.documentElement.classList.add('long-press-animation');
  }, 400)
})
document.addEventListener('mousemove', (e)=>{
  if(down){
    let x = e.screenX - clientX;
    let y = e.screenY - clientY;
    ipcRenderer.sendTo(window.senderId, "setPosition", {x,y, width: docWidth, height: docHeight});
  }else{
    if(e.clientX !== clientX && e.clientY !== clientY){
      clearTimeout(timeoutId);
    }
    down = false;
    clientX = 0;
    clientY = 0;
  }
})
let state;
document.addEventListener('mouseup', (e)=>{
  e.preventDefault();
  e.stopPropagation();
  
  if(down){
    state = true;
    if(window.sendSaveData){
      let data = window.getData();
      window.sendSaveData(data);
    }
  }else{
    state = false;
  }

  down = false;
  document.documentElement.classList.remove('long-press-animation')
  clearTimeout(timeoutId);
})

document.addEventListener('mouseleave', (e)=>{
  if(!down)return;
  clientX = 0;
  clientY = 0;
  down = false;
  document.documentElement.classList.remove('long-press-animation')
  clearTimeout(timeoutId);
})

window.triggerHandle = (cd) => {
  return function (){
    
    if(state)return;
    cd.apply(this, arguments);
  }
  
}